package com.lixl.activemq;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public abstract class AbstractActiveMQThread extends Thread {

	Connection connection = null;
	Session session = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;

	public AbstractActiveMQThread() throws JMSException {
		this(ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD,
				ActiveMQConnection.DEFAULT_BROKER_URL);
	}

	public AbstractActiveMQThread(String userName, String password,
			String brokerURL) throws JMSException {
		//创建工厂
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, brokerURL);
		//创建连接
		connection = factory.createConnection();
		//启动连接
		connection.start();
		//创建会话
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		//session = connection.createSession(true, Session.SESSION_TRANSACTED);//消息持久化
	}

	/**
	 * 创建队列类型数据的生产者
	 * @param queueName
	 * @throws JMSException
	 */
	public void creatQueueProducer(String queueName) throws JMSException {
		producer = session.createProducer(session.createQueue(queueName));
	}

	/**
	 * 创建队列类型数据的消费者
	 * @param queueName
	 * @throws JMSException
	 */
	public void createQueueConsumer(String queueName) throws JMSException {
		consumer = session.createConsumer(session.createQueue(queueName));
	}

	public void close(){
		if(consumer!=null){
			try {
				consumer.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if(producer!=null){
			try {
				producer.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if(session!=null){
			try {
				session.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if(connection!=null){
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
	}

}
